package com.huika.dealontop.control.myinfo.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.myinfo.adapter.MyOrderListAdapter;
import com.huika.dealontop.control.myinfo.adapter.OrderListFilterAdapter;
import com.huika.dealontop.support.domain.FilterBeanTwo;
import com.huika.dealontop.support.domain.MyOrderItemBean;
import com.huika.dealontop.support.event.CallMainPagerChangeEvent;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.support.http.ServerFlagError;
import com.huika.dealontop.support.http.ServerJsonUnParseError;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.TitleBarHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Author: Victor CaiLu
 * <p/>
 * Description: 我的订单
 */
public class MyOrderListActivity extends BaseAct {
    private PullToRefreshListView mPullRefreshListView;
    private List<MyOrderItemBean> MyOrderItemList = new ArrayList<MyOrderItemBean>();
    private MyOrderListAdapter MyOrderListGrouponAdapter;
    private JSONWrapAjaxParams ajaxParams;
    private FormResultRequest<List<MyOrderItemBean>> mOrderListRequest;
    private PopupWindow pop;
    private View layouts;
    private ListView lv_seleteArea_left;
    private View mInflate;
    private OrderListFilterAdapter mOrderListFilterAdapter;
    private List<FilterBeanTwo> filterlist = new ArrayList<FilterBeanTwo>();
    private View mblackView;
    private LinearLayout mEmpty_orderList;
    private int mKey;
    private TextView mInstantShop;
    private ImageView mIvBackToTop;

    @Override
    public void setRootView() {

        mInflate = View.inflate(this, R.layout.activity_orderlist, null);

        setContentView(mInflate);
    }

    public static String CONTENTKEY = "key";

    @Override
    protected void initWidget() {
        super.initWidget();

        mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
        mblackView = findViewById(R.id.orderlist_view);
        mEmpty_orderList = (LinearLayout) findViewById(R.id.myorderList_Empty_View);
        mKey = getIntent().getIntExtra(CONTENTKEY, 0);
        mIvBackToTop = (ImageView) findViewById(R.id.iv_back_to_top);

        mInstantShop = (TextView) findViewById(R.id.click_reload);

        assignSeleteViews();
        initTitle();
        InitAapter();
        initListener();
    }

    private void InitAapter() {
        mOrderListFilterAdapter = new OrderListFilterAdapter(this);
        filterlist.add(new FilterBeanTwo(getString(R.string.myorder_list_filter_all), false, 0));
        filterlist.add(new FilterBeanTwo(getString(R.string.myorder_list_filter_nopay), false, 1));
        filterlist.add(new FilterBeanTwo(getString(R.string.myorder_list_filter_nouse), false, 2));
        filterlist.add(new FilterBeanTwo(getString(R.string.myorder_list_has_use), false, 3));
        filterlist.add(new FilterBeanTwo(getString(R.string.myorder_list_filter_backprice), false, 4));
        filterlist.add(new FilterBeanTwo(getString(R.string.myorder_list_has_expired), false, 5));
        filterlist.add(new FilterBeanTwo(getString(R.string.myorder_list_filter_alreadycancle), false, 6));
        filterlist.add(new FilterBeanTwo(getString(R.string.myorder_list_filter_readycomment), false, 7));
        FilterBeanTwo filterBeanTwo = null;
        switch (mKey) {

            case 0:
                filterBeanTwo = filterlist.get(0);
                break;
            case 1:
                filterBeanTwo = filterlist.get(1);
                break;
            case 2:
                filterBeanTwo = filterlist.get(2);
                break;
            case 3:
                filterBeanTwo = filterlist.get(7);
                break;


        }
        filterBeanTwo.setIsSelete(true);
        mOrderListFilterAdapter.setPreviousFilterBean(filterBeanTwo);

        mOrderListFilterAdapter.setGroup(filterlist);

    }

    /**
     * 注册弹出框的布局
     */
    private void assignSeleteViews() {
        final LayoutInflater inflater = LayoutInflater.from(this);
        layouts = inflater.inflate(R.layout.include_right_block, null);
        TitleBarHelper titleBarHelper = new TitleBarHelper(layouts, R.string.common_empty, R.string.common_empty, R.string.myorder_list_filter);
        //确定按钮取消
        //titleBarHelper.setRightMsg(getString(R.string.myorder_list_filter_enter));
//        titleBarHelper.setOnRightClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                executeGetNearbyGrouponPro();
//                pop.dismiss();
//
//            }
//        });
        titleBarHelper.setOnLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
            }
        });
        lv_seleteArea_left = (ListView) layouts.findViewById(R.id.myorderlist_float_lv);

    }

    private void initTitle() {
        TitleBarHelper titleBarHelper = new TitleBarHelper(this, R.string.common_empty, R.string.common_empty, R.string.myorder_list);
        titleBarHelper.setRightMsg(getString(R.string.myorder_list_filter));
        titleBarHelper.setOnRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lv_seleteArea_left.setAdapter(mOrderListFilterAdapter);
                openPopWindow();

            }
        });
    }


    /***
     * 弹出自定义的菜单
     ***/
    public void openPopWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
        }

        if (pop == null) {
            DisplayMetrics dm = new DisplayMetrics();

            getWindowManager().getDefaultDisplay().getMetrics(dm);

            int width = dm.widthPixels;//宽度

            int height = dm.heightPixels;//高度
            pop = new PopupWindow(layouts, width, height, true);
            pop.setAnimationStyle(R.style.AnimationFade);
            pop.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            // 设置popupwindow可点击
            pop.setTouchable(true);
            // 设置popupwindow外部可点击
            pop.setOutsideTouchable(true);
            // 获取焦点
            pop.setFocusable(true);
            //在这里设置背景才不会出现Selector的问题
            //设置popwindow大小
            pop.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R
                    .color.common_black)));
            pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mblackView.setVisibility(View.GONE);
                }
            });
        }
        /* 设置popupwindow的位置 */
        pop.showAtLocation(mInflate, Gravity.LEFT, 0, 0);
        pop.update();
        mblackView.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            executeGetNearbyGrouponPro();
        }
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);

        switch (v.getId()) {
            case R.id.click_reload:
                aty.finish();
                EventBus.getDefault().post(new CallMainPagerChangeEvent(1));
                break;
            case R.id.iv_back_to_top:
                if (android.os.Build.VERSION.SDK_INT >= 8) {
                    mPullRefreshListView.getRefreshableView().smoothScrollToPosition(0);
                } else {
                    mPullRefreshListView.getRefreshableView().setSelection(0);
                }
                break;
        }

    }

    private void changeRefreshMode(int totalSize) {
        if (totalSize == 0) {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
        } else {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        }
    }

    private void initListener() {
        mInstantShop.setOnClickListener(this);
        mIvBackToTop.setOnClickListener(this);
        lv_seleteArea_left.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //mCurrenFilterIndex = position;
                if (mOrderListFilterAdapter.getPreviousFilterBean() != mOrderListFilterAdapter.getItem(position)) {
                    if (mOrderListFilterAdapter.getPreviousFilterBean() != null) {
                        mOrderListFilterAdapter.getPreviousFilterBean().isSelete = false;
                    }
                    mOrderListFilterAdapter.setPreviousFilterBean(mOrderListFilterAdapter.getItem(position));

                    mOrderListFilterAdapter.getItem(position).isSelete = !mOrderListFilterAdapter.getItem(position).isSelete;
                    mOrderListFilterAdapter.notifyDataSetChanged();
                    executeGetNearbyGrouponPro();
                    pop.dismiss();
                }
            }
        });


        MyOrderListGrouponAdapter = new MyOrderListAdapter(UIUtils.getContext());

        mPullRefreshListView.getlv().setDivider(new ColorDrawable(UIUtils.getColor(R.color.common_bg)));
        mPullRefreshListView.getlv().setDividerHeight(UIUtils.dip2px(8));
        mPullRefreshListView.setAdapter(MyOrderListGrouponAdapter);
        mPullRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String orderId = String.valueOf(MyOrderListGrouponAdapter.getItem(i - 1).getOrderID());
                Intent intent = new Intent(MyOrderListActivity.this, OrderDetailActivity.class);
                intent.putExtra(OrderDetailActivity.ORDER_ID, orderId);
                //随便来个结果码
                startActivityForResult(intent, 0);

            }
        });

        executeGetNearbyGrouponPro();
        mPullRefreshListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem >= 4) {
                    if (mIvBackToTop.getVisibility() != View.VISIBLE)
                        mIvBackToTop.setVisibility(View.VISIBLE);
                } else if (firstVisibleItem < 3) {
                    if (mIvBackToTop.getVisibility() != View.GONE)
                        mIvBackToTop.setVisibility(View.GONE);
                }
            }
        });
        mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>()

                                                  {
                                                      @Override
                                                      public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                                                          executeGetNearbyGrouponPro();
                                                      }

                                                      @Override
                                                      public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                                                          CURRENT_PAGE++;
                                                          ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
                                                          executeRequest(mOrderListRequest);

                                                      }
                                                  }

        );
    }

    public int getMtype() {
        return mtype;
    }

    public void setMtype(int mtype) {
        this.mtype = mtype;
    }


    private int mtype = 0;

    private void executeGetNearbyGrouponPro() {

        long userId = GlobalApp.getInstance().getUserId();

        CURRENT_PAGE = 1;
        if (mOrderListFilterAdapter.getPreviousFilterBean() != null) {
            mtype = mOrderListFilterAdapter.getPreviousFilterBean().getFilter_ID();
        }


        ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("userID", userId);//用户ID(RSA加密)
        ajaxParams.putCommonTypeParam("type", mtype);//0.全部 1.待付款 2.未使用 3.已使用 4.退款 5.已过期6.已取消 7.待评价
        ajaxParams.putCommonTypeParam("pageSize", PAGE_SIZE);
        ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);

        mOrderListRequest = new FormResultRequest<List<MyOrderItemBean>>
                (UrlConstants.MYORDERBOOK, GetNearbyGrouponPro, this, new TypeToken<RequestResult<List<MyOrderItemBean>>>() {
                }.getType());
        mOrderListRequest.setRequestParams(ajaxParams);
        showLoadingDialog("");
        executeRequest(mOrderListRequest);
    }

    private Response.Listener<RequestResult<List<MyOrderItemBean>>> GetNearbyGrouponPro = new
            Response.Listener<RequestResult<List<MyOrderItemBean>>>() {
                @Override
                public void onResponse(RequestResult<List<MyOrderItemBean>> Result) {
                    dismissLoadingDialog();
                    mPullRefreshListView.onRefreshComplete();
                    int totalSize = Result.getTotalSize();
                    if (Result.flag == 1) {

                        if (Result != null && Result.getRs() != null) {
                            //无数据
                            if (CURRENT_PAGE == 1) {
                                MyOrderItemList = Result.getRs();
                            } else {
                                MyOrderItemList.addAll(Result.getRs());
                            }
                            MyOrderListGrouponAdapter.setGroup(MyOrderItemList);

                            if (MyOrderItemList.size() <= 0) {// 无记录
                                // hideOverLay();
                                //showToastMsg("数据为空");
                                mEmpty_orderList.setVisibility(View.VISIBLE);
                            } else {
                                if (mEmpty_orderList.getVisibility() == View.VISIBLE) {
                                    mEmpty_orderList.setVisibility(View.GONE);
                                }
                            }
                        }
                    }
                }
            };

    /**
     * 点击列表条目的监听事件
     */
    private void SelectContentItemView() {
        mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                executeGetNearbyGrouponPro();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                CURRENT_PAGE++;
                ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
                executeRequest(mOrderListRequest);

            }
        });
        mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        MyOrderListGrouponAdapter = new MyOrderListAdapter(UIUtils.getContext());
        mPullRefreshListView.setAdapter(MyOrderListGrouponAdapter);
        if (MyOrderListGrouponAdapter.getCount() == 0) {
            onInitShow();
        }
    }

    public void onInitShow() {
        hideOverLay();
        //showLoadingDialog(getString(R.string.common_loading));
        executeGetNearbyGrouponPro();
    }

    // 默认网络请求异常回调
    @Override
    public void onErrorResponse(VolleyError error) {
        dismissLoadingDialog();
        if (CURRENT_PAGE > 1) {// 加载异常回退到当前页
            CURRENT_PAGE--;
        }
        String msg = getResources().getString(R.string.error_response);
        if (error instanceof ServerFlagError) {
            msg = ((ServerFlagError) error).result.msg;
        } else if (error instanceof ServerJsonUnParseError) {
            try {
                String res = ((ServerJsonUnParseError) error).result;
                JSONObject jsonObject = new JSONObject(res);
                msg = jsonObject.getString("msg");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            try {
                if (error.networkResponse != null
                        && error.networkResponse.data != null) {
                    msg = new String(error.networkResponse.data, "utf-8");
//                    if (TextUtils.isEmpty(msg)) {
//                        msg = "未知异常";
//                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (!TextUtils.isEmpty(msg)) {
            showToastMsg(msg);
        }
    }


}
